#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 日志函数
log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# 检测操作系统
check_os() {
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        if [ -f /etc/redhat-release ]; then
            OS="centos"
            OS_VERSION=$(cat /etc/redhat-release | grep -oE '[0-9]+' | head -1)
        elif [ -f /etc/lsb-release ]; then
            . /etc/lsb-release
            OS="ubuntu"
            OS_VERSION=$DISTRIB_RELEASE
        elif [ -f /etc/debian_version ]; then
            OS="debian"
            OS_VERSION=$(cat /etc/debian_version)
        else
            OS="unknown"
        fi
    else
        log_error "不支持的操作系统: $OSTYPE"
        exit 1
    fi
    
    log_info "检测到操作系统: $OS $OS_VERSION"
}

# 检查命令是否存在
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# 检查Docker
check_docker() {
    if command_exists docker; then
        DOCKER_VERSION=$(docker --version | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
        log_success "Docker 已安装 (版本: $DOCKER_VERSION)"
        return 0
    else
        log_warning "Docker 未安装"
        return 1
    fi
}

# 检查Docker Compose
check_docker_compose() {
    if docker compose version >/dev/null 2>&1; then
        COMPOSE_VERSION=$(docker compose version | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
        log_success "Docker Compose 已安装 (版本: $COMPOSE_VERSION)"
        return 0
    else
        log_warning "Docker Compose 未安装"
        return 1
    fi
}

# 检查系统要求
check_system_requirements() {
    log_info "检查系统要求..."
    
    # 检查内存
    TOTAL_MEM=$(free -m | awk 'NR==2{print $2}')
    if [ $TOTAL_MEM -lt 2048 ]; then
        log_warning "系统内存不足 (当前: ${TOTAL_MEM}MB, 建议: >=2048MB)"
    else
        log_success "系统内存充足 (${TOTAL_MEM}MB)"
    fi
    
    # 检查磁盘空间
    DISK_SPACE=$(df -BG / | awk 'NR==2{print $4}' | sed 's/G//')
    if [ $DISK_SPACE -lt 10 ]; then
        log_warning "磁盘空间不足 (可用: ${DISK_SPACE}GB, 建议: >=10GB)"
    else
        log_success "磁盘空间充足 (可用: ${DISK_SPACE}GB)"
    fi
    
    # 检查CPU核心数
    CPU_CORES=$(nproc)
    if [ $CPU_CORES -lt 2 ]; then
        log_warning "CPU核心数较少 (当前: ${CPU_CORES}, 建议: >=2)"
    else
        log_success "CPU核心数充足 (${CPU_CORES}核)"
    fi
}

# 安装Docker (Ubuntu/Debian)
install_docker_debian() {
    log_info "开始安装Docker..."
    
    # 更新包索引
    sudo apt-get update
    
    # 安装依赖
    sudo apt-get install -y \
        apt-transport-https \
        ca-certificates \
        curl \
        gnupg \
        lsb-release
    
    # 添加Docker官方GPG密钥
    curl -fsSL https://download.docker.com/linux/$OS/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
    
    # 设置稳定版仓库
    echo \
        "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/$OS \
        $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
    
    # 安装Docker Engine
    sudo apt-get update
    sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
    
    # 启动Docker
    sudo systemctl start docker
    sudo systemctl enable docker
    
    # 将当前用户添加到docker组
    sudo usermod -aG docker $USER
    
    log_success "Docker安装完成"
}

# 安装Docker (CentOS/RHEL)
install_docker_centos() {
    log_info "开始安装Docker..."
    
    # 卸载旧版本
    sudo yum remove -y docker \
                     docker-client \
                     docker-client-latest \
                     docker-common \
                     docker-latest \
                     docker-latest-logrotate \
                     docker-logrotate \
                     docker-engine
    
    # 安装依赖
    sudo yum install -y yum-utils
    
    # 设置仓库
    sudo yum-config-manager \
        --add-repo \
        https://download.docker.com/linux/centos/docker-ce.repo
    
    # 安装Docker Engine
    sudo yum install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
    
    # 启动Docker
    sudo systemctl start docker
    sudo systemctl enable docker
    
    # 将当前用户添加到docker组
    sudo usermod -aG docker $USER
    
    log_success "Docker安装完成"
}

# 安装Docker
install_docker() {
    case $OS in
        ubuntu|debian)
            install_docker_debian
            ;;
        centos)
            install_docker_centos
            ;;
        *)
            log_error "不支持的操作系统: $OS"
            exit 1
            ;;
    esac
}

# 主函数
main() {
    log_info "开始环境检测..."
    
    # 检测操作系统
    check_os
    
    # 检查系统要求
    check_system_requirements
    
    # 检查Docker
    if ! check_docker; then
        read -p "是否安装Docker? (y/n): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            install_docker
        else
            log_error "Docker是必需的，请手动安装后重试"
            exit 1
        fi
    fi
    
    # 检查Docker Compose
    if ! check_docker_compose; then
        log_info "Docker Compose将通过Docker插件提供"
    fi
    
    # 检查Docker服务状态
    if sudo systemctl is-active --quiet docker; then
        log_success "Docker服务正在运行"
    else
        log_warning "Docker服务未运行，正在启动..."
        sudo systemctl start docker
    fi
    
    log_success "环境检测完成，所有依赖都已满足"
}

# 执行主函数
main "$@"